#include "clientsocket.h"
#include "network/tlpacket.h"
#include "utils/Config.h"
#include "main.h"

ClientSocket::ClientSocket(QObject *parent) :
    QTcpSocket(parent), waitingdata(false)
{
    connect(this,SIGNAL(readyRead()),this,SLOT(OnData()));
    QString fakedata("000000");
    dumper = new Packets::TLPacket(fakedata);
    //connect(this,SIGNAL(bytesWritten(qint64),this,SLOT(OnSend(quint64))));
}
void ClientSocket::OnData()
{
    QByteArray data = readAll();        //Read all data
    if(data.isEmpty())
        return;

    if(waitingdata)
    {
         wdata.append(data);
         wdata.clear();
    }

    QByteArray cmddata;
    Packets::TLPacket::pheader head;
    QBuffer buff(&data);
    buff.open(QBuffer::ReadWrite);
    QDataStream idata(&buff);

    while(!idata.atEnd())
    {
        idata >> head.cmd;
        idata >> head.size;
        if(head.size>idata.device()->bytesAvailable())
        {
             idata << head.cmd;
             idata << head.size;
             wdata.resize(idata.device()->bytesAvailable());
             idata.readRawData((char*)(wdata.data()+3),idata.device()->bytesAvailable());
        }else{
            cmddata.resize((int)head.size);
            idata.readRawData(cmddata.data(),head.size);
            Packets::TLPacket pkt(head,cmddata);
           if(DEBUG_TCP_RECV && FILTER_TCP(head.cmd)){
                QString outp=tr("RecvFrom %1:%2").arg(peerAddress().toString()).arg(peerPort());
                outp+=dumper->StDump((*pkt.GetRaw()));
                _log->LogIt(outp,Logg::IDEBUG);
            }
            emit OnPacket(pkt);
        }
    }
}
void ClientSocket::OnSend(quint64)
{

}
void ClientSocket::Send(Packets::TLPacket &packet){
    SendData((*packet.GetRaw()));
}
void ClientSocket::Send(QByteArray data){
    SendData(data);
}
void ClientSocket::Send(char* data, quint32 size){
    QByteArray bdata(data,size);
    SendData(bdata);
}

void ClientSocket::SendData(QByteArray data){
    write(data);
    waitForBytesWritten();
    if(DEBUG_TCP_SEND && FILTER_TCP((quint16)(*data.data()))){
        QString outp=tr("SendTo %1:%2").arg(peerAddress().toString()).arg(peerPort());
        outp+=dumper->StDump(data);
        _log->LogIt(outp,Logg::ODEBUG);
    }
}
